﻿using InfonavaEye.components;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace InfonavaEye.util
{
    public class HttpTools
    {
        private static HttpTools instance;
        #region properties

        private readonly Encoding ENCODING = Encoding.UTF8;
        #endregion

        #region constructor
        public HttpTools()
        {
        }

        public static HttpTools getInstance() {
            if (instance==null)
            {
                  instance = new HttpTools();
            }
            return instance;
        }
        #endregion

        #region public methods

        /// <summary>
        /// Post
        /// </summary>
        /// <param name="url"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public string HTTPJsonPost(string url, string msg)
        {
            string result = string.Empty;
            try
            {
                Console.WriteLine("HTTPJsonPost url:{0} content:{1}",url, msg);
                result = CommonHttpRequest(msg, url, "POST");
            }
            catch (WebException ex)
            {
                if (ex.Response != null)
                {
                    HttpWebResponse response = (HttpWebResponse)ex.Response;
                    Console.WriteLine("Error code: {0}", response.StatusCode);
                    switch (response.StatusCode)
                    {
                        case HttpStatusCode.BadRequest:
                        case HttpStatusCode.Forbidden:
                        case HttpStatusCode.InternalServerError:
                            {
                                using (Stream data = response.GetResponseStream())
                                {
                                    using (StreamReader reader = new StreamReader(data))
                                    {
                                        string text = reader.ReadToEnd();
                                        throw new Exception(text);
                                    }
                                }
                            }
                            break;
                    }

                }
                Console.WriteLine("HTTPJsonPost异常:{0}", ex.Message);
            }
            catch (Exception ex)
            {
                Console.WriteLine("HTTPJsonPost异常:{0}", ex.Message);
                throw new Exception(ex.Message);

            }
            return result;
        }


        public T request<T>(String jsonData, String url, string type) {
            try
            {
                var res = "";
                if ("POST".Equals(type))
                {
                    res = this.HTTPJsonPost(url, jsonData);
                }
                if ("GET".Equals(type))
                {
                    res = this.HTTPJsonGet(url);
                }
                if (!string.IsNullOrEmpty(res))
                {
                    T result = JsonConvert.DeserializeObject<T>(res);
                    return result;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("服务器请求异常，" + ex.Message);
                Console.WriteLine("上报失败，异常：{0}", ex);
            }
            return default(T);
        }
        /// <summary>
        /// Get
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public string HTTPJsonGet(string url)
        {
            string result = string.Empty;
            try
            {
                Console.WriteLine("HTTPJsonPostUrl:{0}", url);
                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
                request.ContentType = "application/json";
                request.Method = "GET";
                HttpWebResponse resp = request.GetResponse() as HttpWebResponse;
                System.IO.StreamReader reader = new System.IO.StreamReader(resp.GetResponseStream(), this.ENCODING);
                result = reader.ReadToEnd();
            }
            catch (Exception ex)
            {
                Console.WriteLine("HTTPJsonGet异常:{0}", ex.Message);
            }
            return result;
        }

        /// <summary>
        /// Put
        /// </summary>
        /// <param name="data"></param>
        /// <param name="uri"></param>
        /// <returns></returns>
        public string HTTPJsonDelete(string url, string data)
        {
            return CommonHttpRequest(data, url, "DELETE");
        }

        /// <summary>
        /// Put
        /// </summary>
        /// <param name="data"></param>
        /// <param name="uri"></param>
        /// <returns></returns>
        public string HTTPJsonPut(string url, string data)
        {
            return CommonHttpRequest(data, url, "PUT");
        }

        #endregion

        #region private

        public string CommonHttpRequest(string data, string uri, string type)
        {

            //Web访问对象，构造请求的url地址
            string serviceUrl = uri;

            //构造http请求的对象
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(serviceUrl);
            myRequest.Timeout = 600000;
            //转成网络流
            byte[] buf = this.ENCODING.GetBytes(data);
            //设置
            myRequest.Method = type;
            myRequest.ContentLength = buf.LongLength;
            myRequest.ContentType = "application/json";


            using (Stream reqstream = myRequest.GetRequestStream())
            {
                reqstream.Write(buf, 0, (int)buf.Length);
            }
            HttpWebResponse resp = null;
            System.IO.StreamReader reader = null;
            string ReturnXml = null;
            try
            {
                 resp = myRequest.GetResponse() as HttpWebResponse;
                 reader = new System.IO.StreamReader(resp.GetResponseStream(), this.ENCODING);
                 ReturnXml = reader.ReadToEnd();
            }
            catch (Exception ex)
            {
                throw new Exception("",ex);
            }
            finally {
                if (reader!=null) {
                    reader.Close();
                }
                if (resp!=null) {
                    resp.Close();
                }
                
            }
            return ReturnXml;
        }
        #endregion

        

    }
}
